<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { batchAddEmployeesList } from '@/api/employees'
export default {
  name: 'Import',
  computed: {
    type() {
      return this.$route.query.type
    }
  },
  methods: {
    handleSuccess({ results, header }) {
      // 从哪个页面跳转就用哪个方法
      if (this.type === 'user') {
        this.batchAddEmployees(results)
      }
    },
    // 批量新增员工
    async batchAddEmployees(results) {
      /* console.log(results)
      console.log(header) */
      // 把中文的键转化为英文的
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const arr = []
      results.forEach(item => {
        const tempObj = {}
        for (const key in item) {
          // 中文的key
          /* console.log(key) */
          // 转化为英文的key
          const englishKey = userRelations[key]
          /* console.log(userRelations[key]) */
          if (['correctionTime', 'timeOfEntry'].includes(englishKey)) {
            tempObj[englishKey] = this.formatExcelDate(item[key])
          } else {
            tempObj[englishKey] = item[key]
          /* console.log(item[key]) */
          }
        }
        arr.push(tempObj)
      })
      await batchAddEmployeesList(arr)
      this.$message.success('导入成功！')
      this.$router.push('/employees/index')
    },
    // 转换excel日期格式
    formatExcelDate(numb, format) {
      const time = new Date((numb) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + '-' + (month < 10 ? '0' + month : month) + '-' + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
